const http = require("http");
const fs = require("fs");
const path = require("path");
const { pipeline } = require("stream");
const Busboy = require("busboy");

const PORT = 5000;
const UPLOAD_DIR = path.join(__dirname, "uploads");

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR);
}

const server = http.createServer((req, res) => {
  // 处理CORS
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");

  if (req.method === "OPTIONS") {
    res.writeHead(200);
    res.end();
    return;
  }

  if (req.url === "/upload" && req.method === "POST") {
    const busboy = Busboy({ headers: req.headers });
    const fileWrites = [];
    let uploadedFileName = "";
    let totalSize = 0;
    let uploadedSize = 0;

    // 获取内容总长度
    totalSize = parseInt(req.headers["content-length"], 10) || 0;

    busboy.on("file", (fieldname, file, info) => {
      const { filename, encoding, mimeType } = info;
      if (!filename) return;

      uploadedFileName = `${Date.now()}-${filename}`;
      const saveTo = path.join(UPLOAD_DIR, uploadedFileName);
      const writeStream = fs.createWriteStream(saveTo);

      file.on("data", (chunk) => {
        uploadedSize += chunk.length;
        const percent = Math.round((uploadedSize / totalSize) * 100);
        console.log(`上传进度: ${percent}%`);
      });

      fileWrites.push(
        new Promise((resolve, reject) => {
          pipeline(file, writeStream, (err) => {
            if (err) reject(err);
            else resolve();
          });
        })
      );
    });

    busboy.on("finish", async () => {
      try {
        await Promise.all(fileWrites);
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(
          JSON.stringify({
            success: true,
            message: "文件上传成功",
            filename: uploadedFileName,
          })
        );
      } catch (err) {
        console.error("上传错误:", err);
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(
          JSON.stringify({
            success: false,
            message: "文件上传失败",
          })
        );
      }
    });

    busboy.on("error", (err) => {
      console.error("Busboy错误:", err);
      res.writeHead(500, { "Content-Type": "application/json" });
      res.end(
        JSON.stringify({
          success: false,
          message: "解析请求失败",
        })
      );
    });

    req.pipe(busboy);
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(
      JSON.stringify({
        success: false,
        message: "接口不存在",
      })
    );
  }
});

server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`文件上传目录: ${UPLOAD_DIR}`);
});
